const axios = require('axios');

const BASE_URL = 'http://localhost:3000/api';

async function testSyncFix() {
  try {
    console.log('测试同步修复...\n');
    
    // 1. 检查初始状态
    console.log('1. 检查初始同步状态:');
    let statusResponse = await axios.get(`${BASE_URL}/sync/status`);
    console.log('- 同步状态:', statusResponse.data.isSyncing ? '进行中' : '空闲');
    console.log('- 进度:', statusResponse.data.progress + '%');
    
    // 2. 启动同步任务
    console.log('\n2. 启动同步任务:');
    const startResponse = await axios.post(`${BASE_URL}/sync/start`, { type: 'full' });
    console.log('- 启动响应:', startResponse.data.message);
    console.log('- 任务类型:', startResponse.data.type);
    
    // 3. 等待一段时间后检查状态
    console.log('\n3. 等待3秒后检查状态:');
    await new Promise(resolve => setTimeout(resolve, 3000));
    
    statusResponse = await axios.get(`${BASE_URL}/sync/status`);
    console.log('- 同步状态:', statusResponse.data.isSyncing ? '进行中' : '空闲');
    console.log('- 进度:', statusResponse.data.progress + '%');
    console.log('- 进度文本:', statusResponse.data.progressText);
    
    // 4. 再等待一段时间检查进度
    console.log('\n4. 等待5秒后再次检查:');
    await new Promise(resolve => setTimeout(resolve, 5000));
    
    statusResponse = await axios.get(`${BASE_URL}/sync/status`);
    console.log('- 同步状态:', statusResponse.data.isSyncing ? '进行中' : '空闲');
    console.log('- 进度:', statusResponse.data.progress + '%');
    console.log('- 进度文本:', statusResponse.data.progressText);
    
    // 5. 检查同步历史
    console.log('\n5. 检查同步历史:');
    const historyResponse = await axios.get(`${BASE_URL}/sync/history`);
    console.log('- 历史记录数量:', historyResponse.data.total);
    if (historyResponse.data.items.length > 0) {
      const latest = historyResponse.data.items[0];
      console.log('- 最新记录状态:', latest.status);
      console.log('- 同步包数:', latest.packagesSynced);
    }
    
    console.log('\n✅ 同步功能测试完成！');
    
  } catch (error) {
    console.error('❌ 测试失败:', error.message);
    if (error.response) {
      console.log('响应状态:', error.response.status);
      console.log('响应数据:', error.response.data);
    }
  }
}

// 等待服务器启动
setTimeout(() => {
  testSyncFix().catch(console.error);
}, 2000);